package com.faxsun.core.persist.dao.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;

import mtons.modules.persist.impl.DaoImpl;
import mtons.modules.pojos.Page;

import com.faxsun.core.persist.dao.LiveMsgDao;
import com.faxsun.core.persist.entity.LiveMsgPO;

public class LiveMsgDaoImpl extends DaoImpl<LiveMsgPO> implements LiveMsgDao {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5383634600978508209L;

	protected LiveMsgDaoImpl() {
		super(LiveMsgPO.class);
	}

	@Override
	public List<LiveMsgPO> listHistory(Page page, long channelId) {
		return listHisotry(page, channelId, 0);
	}

	@Override
	public List<LiveMsgPO> listHisotry(Page page, long channelId, long msgId) {
		PagingQuery<LiveMsgPO> msgQuery = pagingQuery(page);
		msgQuery.desc("date");
		msgQuery.desc("id");
		if (msgId > 0) {
			msgQuery.add(Restrictions.lt("id", msgId));
		}
		msgQuery.add(Restrictions.eq("channel.id", channelId));
		List<LiveMsgPO> result = msgQuery.list();
		Collections.sort(result, new Comparator<LiveMsgPO>() {

			@Override
			public int compare(LiveMsgPO o1, LiveMsgPO o2) {

				Long o1Id=new Long(o1.getId());
				Long o2Id=new Long( o2.getId());
				return o1Id.compareTo(o2Id);
			}
		});
		return result;
	}

	@Override
	public List<LiveMsgPO> listNew(Page page, long channelId, long msgId) {
		PagingQuery<LiveMsgPO> msgQuery = pagingQuery(page);
		msgQuery.asc("date");
		msgQuery.asc("id");
		if (msgId > 0) {
			msgQuery.add(Restrictions.gt("id", msgId));
		}
		msgQuery.add(Restrictions.eq("channel.id", channelId));
		List<LiveMsgPO> result = msgQuery.list();
		return result;
	}

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public List<Date> findMsgDateById(long channelId) {
        Query q = super.createQuery(
                "SELECT DATE(date) FROM LiveMsgPO WHERE channel.id=? GROUP BY DATE(date) ORDER BY DATE(date) DESC", channelId);
        List list = q.list();
        return list;
    }

}
